<template>
  <PageWrapper :title="t('routes.menu.<%= data.name %>') + t('common.edit')" class="pb-12">
    <template #subTitle> {{ detailRef.BillId }} </template>
    <template #extra>
      <a-button type="primary" @click="submitAll(false)" class="mx-4">
        {{ t('common.saveText') }}
      </a-button>
      <a-button type="primary" @click="submitAll(true)"> {{ t('common.saveAndSubmit') }} </a-button>
    </template>
    <Block :title="t('common.billDes')">
      <BasicForm @register="register" @field-value-change="fieldChange" />
    </Block>
    <Block :title="t('common.editDetails')" :wrapper="false">
      <BasicTable @register="registerTable">
        <template #toolbar>
          <a-button type="primary" @click="editDetails">
            {{ t('common.selectDetails') }}
          </a-button>
        </template>
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'action'">
            <TableAction
              :actions="[
                {
                  icon: 'ant-design:delete-outlined',
                  color: 'error',
                  tooltip: t('common.delText'),
                  popConfirm: {
                    title: t('common.isDel'),
                    placement: 'left',
                    confirm: handleDelete.bind(null, record),
                  },
                },
              ]"
            />
          </template>
        </template>
      </BasicTable>
    </Block>
    <!-- 附件列表 -->
    <Annex @file-change="(e) => (detailRef.BillFiles = e)" :fileId="detailRef.BillId" />
    <MaterialModal @register="modalRegister" @success="getMaterial" />
  </PageWrapper>
</template>
<script lang="ts" setup name="<%= data.name %>_Edit">
  // ----------------------------- 第三方引入 -----------------------------
  import { unref, onMounted, ref } from 'vue';
  // ----------------------------- hooks -----------------------------
  import { useI18n } from '/@/hooks/web/useI18n';
  import { useAppRouter } from '/~/hooks/help/useAppRouter';
  import { useAppEditTable } from '/~/hooks/help/useAppTable';
  import { useAppForm } from '/~/hooks/help/useAppForm';
  import { useTax } from '/~/hooks/work/useTax';
  // ----------------------------- 组件 -----------------------------
  import { BasicForm } from '/@/components/Form';
  import { BasicTable, TableAction } from '/@/components/Table';
  import { MaterialModal, useModal } from '/~/components/MaterialModal';
  import { PageWrapper } from '/@/components/Page';
  import { Annex } from '/~/components/Annex';
  // ----------------------------- 其他引入 -----------------------------
  import { formSchemas, tableColumns } from './schema.data';
  import <%= data.alias %>Api from '/@/api/work/<%= data.api %>';
  //----------------------------- 变量声明区 -----------------------------
  const detailRef = ref<Recordable>({});
  // ----------------------------- hooks使用区 -----------------------------
  const { closeTo, currentRoute } = useAppRouter();
  const { t } = useI18n();
  const [modalRegister, { openModal }] = useModal();
  const { getTax, taxChange, taxChangeWarning } = useTax('customer');
  const [register, { validateFields, setFieldsValue, getFieldsValue }] = useAppForm({
    layout: 'vertical',
    schemas: formSchemas,
  });
  const [
    registerTable,
    {
      insertTableDataRecord,
      setTableData,
      getDataSource,
      deleteTableDataRecord,
      updateTableColData,
    },
  ] = useAppEditTable({
    columns: tableColumns,
    dataSource: [],
  });
  // ----------------------------- 钩子函数区 -----------------------------
  onMounted(async () => {
    console.log(unref(currentRoute).query);

    const { Id, redo } = unref(currentRoute).query;
    if (Id) {
      let res = await <%= data.alias %>Api.api_get({ BillId: Id });
      redo && delete res.BillId;
      await setFieldsValue(res);
      taxChange(res.CustomerId);
      setTableData(res.BillItems);
      detailRef.value = res;
    }
  });
  //  ----------------------------- 自定义方法区 -----------------------------
  // 删除明细项
  function handleDelete(record: Recordable) {
    // 通过绑定的rowKey删除
    deleteTableDataRecord(unref(record).ItemId);
  }
  function getMaterial(selects: Recordable[]) {
    insertTableDataRecord(
      selects.map((item) => {
        return {
          ...item,
          Tax: getTax(),
        };
      }),
    );
  }
  // 选择 编辑明细
  async function editDetails() {
    await validateFields();
    openModal(true, {
      details: getDataSource(),
    });
  }
  // 提交
  async function submitAll(SaveAndSubmit = false) {
    try {
      let formFieldsValue = await validateFields();
      let params = {
        ...detailRef.value,
        // 保存并提交 或者 保存
        SaveAndSubmit,
        BillItems: getDataSource(),
        ...formFieldsValue,
      };
      console.log(formFieldsValue, detailRef.value);

      let Id = await <%= data.alias %>Api.api_save(params);
      Id &&
        closeTo({
          name: '<%= data.name %>_Detail',
          query: {
            Id,
          },
        });
    } catch (error) {
      console.log('not passing', error);
    }
  }
  function fieldChange(key) {
    if (key === 'CustomerName') {
      taxChangeWarning(getFieldsValue()['CustomerId'], updateTableColData);
    }
  }
</script>
